package com.attedu.jdbc.homework2;

import com.attedu.jdbc.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author tune_the last
 * @date 2025/11/4 - 19:08
 */
public class Reg {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql1 = "SELECT id FROM user WHERE username = ?";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            Scanner in = new Scanner(System.in);
            System.out.print("请输入您的用户名：");
            String username = in.nextLine();
            ps1.setString(1, username);
            ResultSet resultSet = ps1.executeQuery();
            if (resultSet.next()){
                System.out.println("用户名已存在，请重新输入！");
                return;
            }
            String sql2 = "INSERT INTO user(username, password,  nickname, age) VALUES (?,?,?,?)";
            PreparedStatement ps2 = connection.prepareStatement(sql2);
            ps2.setString(1, username);
            System.out.print("请设置登录密码：");
            ps2.setString(2, in.nextLine());
            System.out.print("请输入昵称：");
            ps2.setString(3, in.nextLine());
            System.out.print("请输入年龄：");
            ps2.setInt(4, in.nextInt());

            int i = ps2.executeUpdate();
            if (i > 0){
                System.out.println("注册成功");
            }else {
                System.out.println("注册失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
